package com.heyu.cgsd.app;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.heyu.cgsd.db.DataDBHelper;
import com.heyu.cgsd.model.bean.RatesBean;
import com.heyu.cgsd.model.http.JsonUtil;
import com.heyu.cgsd.util.SharePreferenceUtils;
import com.heyu.cgsd.util.SharedPreferencesUtil;
import com.qmuiteam.qmui.arch.QMUISwipeBackActivityManager;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class CgsdApp extends Application {

    public static Context context;
    private DataDBHelper testDBHelper;

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        SharedPreferencesUtil.getInstance(context);
        QMUISwipeBackActivityManager.init(this);
        initData();
    }

    private void initData() {
        if (SharePreferenceUtils.containKey(this, "first")) {
            return;
        } else {
            SharePreferenceUtils.putBoolean(this, "first", true);
            DateFormat dateFormat = SimpleDateFormat.getDateInstance();
            String nowStr = dateFormat.format(new Date());
            SharePreferenceUtils.putString(this, "now", nowStr);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonStr = JsonUtil.getJsonString(getApplicationContext(), "rates.json");
                List<RatesBean> ratesBeanList = new Gson().fromJson(jsonStr, new TypeToken<List<RatesBean>>() {
                }.getType());
                int size = ratesBeanList.size();
                RatesBean ratesBean;
                testDBHelper = DataDBHelper.getInstance(getApplicationContext());
                SQLiteDatabase db = testDBHelper.getDB();
                db.beginTransaction();
                for (int i = 0; i < size; i++) {
                    ratesBean = ratesBeanList.get(i);
                    testDBHelper.insert("currency", new String[]{"titles", "units", "rates"}, new String[]{ratesBean.getName(), ratesBean.getUnit(), ratesBean.getRate()});
                }
                db.setTransactionSuccessful();
                db.endTransaction();
            }
        }).start();
    }
}